package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;


import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
        private static DataSource ds;
        static {
            try {
            	/*
            	 * 创建connetion对象 从连接池获取连接
            	 * 需要把数据库的用户名,密码,驱动,地址。。。。配置上去
            	 * */
                //加载配置文件
                Properties pro=new Properties();
                InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
                pro.load(is);
                //通过工厂获取连接池对象
                ds = DruidDataSourceFactory.createDataSource(pro);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //获取连接
        public static Connection getConnection() throws SQLException, SQLException {
            return ds.getConnection();
        }
        //获取数据库连接对象
        public static DataSource getDataSource(){
            return ds;
        }
        //重载close方法
        public static void close(Statement stmt, Connection conn){
            close(null,stmt,conn);
        }
        //释放资源
        public static void close(ResultSet rs , Statement stmt, Connection conn){
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }


            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();//归还连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }



